import services from '@/services/quartz';
import {ActionType, PageContainer, ProColumns, ProTable,} from '@ant-design/pro-components';
import {Button, Dropdown, message, Modal, Tooltip} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import CreateRecurringFormProps from './components/CreateRecurringForm';
import CreateDelayForm from './components/CreateDelayForm';
import moment from 'moment';
import {DownOutlined} from '@ant-design/icons';
import ResetJob from './components/ResetJob';

const {pageJob,addDelay,addRecurring,quartzDelete,quartzPause,quartzRes,quartzResume,quartzRun} = services.QzController;


/**
 *  删除任务
 * @param jobName
 */
const handleRemove = async (jobName: string) => {
    const hide = message.loading('正在删除');
    if (!jobName) return true;
    try {
        await quartzDelete(jobName);
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        // message.error('删除失败，请重试');
        return false;
    }
};

/**
 *  暂停任务
 * @param jobName
 */
const handlePause = async (jobName: string) => {
    const hide = message.loading('正在暂停');
    if (!jobName) return true;
    try {
        await quartzPause(jobName);
        hide();
        message.success('暂停成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};


/**
 *  重置任务
 * @param jobName
 */
const handleRes = async (params: API.Res) => {
    const hide = message.loading('正在重置');
    if (!params) return true;
    try {
        await quartzRes(params);
        hide();
        message.success('重置成功');
        return true;
    } catch (error) {
        hide();
        // message.error('删除失败，请重试');
        return false;
    }
};

/**
 *  重启任务
 * @param jobName
 */
const handleResume = async (jobName: string) => {
    const hide = message.loading('正在重启');
    if (!jobName) return true;
    try {
        await quartzResume(jobName);
        hide();
        message.success('重启成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};


/**
 *  手动执行一次
 * @param jobName
 */
const handleRun = async (jobName: string) => {
    const hide = message.loading('正在执行');
    if (!jobName) return true;
    try {
        await quartzRun(jobName);
        hide();
        message.success('执行成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};






const TableList: React.FC<unknown> = () => {
    const [createRecurringModalVisible, handleRecurringModalVisible] = useState<boolean>(false);
    const [createDelayModalVisible, handleDelayModalVisible] = useState<boolean>(false);
    const [resetModalVisible, handleResetModalVisible] = useState<boolean>(false);
    const [stepFormValues, setStepFormValues] = useState({});
    const actionRef = useRef<ActionType>();
    const [current, setCurrent] = useState(1); // 当前页码
    const [pageSize, setPageSize] = useState(10); // 每页显示条数
    // 元数据
    const [jobMetas, setJobMetas] = useState({});;

    // 获取所有元数据
    async function findJobMetas() {
        const response = await services.QrtzClazzMetaController.listsClazzMeta();
        const jobMetasEnumMap: Record<string, { text: string; status: string }> = {};
        if (response && Array.isArray(response.data)) {
            const metaData = response.data;
            // 将数据转换为valueEnum格式
            metaData.reduce((acc, item) => {
                acc[item.clazz] = {text: item.name, status: item.clazz};
                return acc;
            }, jobMetasEnumMap);
            setJobMetas(jobMetasEnumMap)
        }
    }
    useEffect(() => {
        findJobMetas()
    }, []);

    const columns: ProColumns<API.JobAndTriggerBO>[] = [
        {
            title: '任务名',
            dataIndex: 'jobName',
            search: false,
            formItemProps: {
                rules: [{ required: true, message: '请输入任务名' }],
              },
        },
        {
            title: '任务分组',
            dataIndex: 'jobGroup',
            hideInForm: true,
            hideInTable: true,
            search: false
        },
        {
            title: '任务元数据',
            dataIndex: 'jobClassName',
            search: false,
            valueEnum: jobMetas,
            formItemProps: {
                rules: [{ required: true, message: '请选择任务元数据' }],
              },
        },
        {
            title: '触发器状态',
            dataIndex: 'triggerState',
            hideInForm: true,
            search: false
        },
        {
            title: '触发器类型',
            dataIndex: 'triggerType',
            valueType: 'text',
            hideInForm: true,
            search: false,
        },
        {
            title: 'cron表达式 ',
            dataIndex: 'cronExpression',
            valueType: 'text',
            tooltip: 'https://www.bejson.com/othertools/cron/',
            search: false,
            copyable: true, // 启用可复制功能
            formItemProps: {
                rules: [{ required: true, message: '请输入cron表达式' }],
            },
        },
        {
            title: '时区',
            dataIndex: 'timeZoneId',
            valueType: 'text',
            hideInForm: true,
            search: false,
        },
        {
            title: '触发器开始时间',
            dataIndex: 'startTime',
            hideInForm: true,
            search: false,
            render: (text) => text ? moment(Number(text)).format('YYYY-MM-DD HH:mm:ss') : '-',
        },
        {
            title: '触发器结束时间',
            dataIndex: 'endTime',
            hideInForm: true,
            search: false,
            render: (text) => text ? moment(Number(text)).format('YYYY-MM-DD HH:mm:ss') : '-',
        },
        {
            title: '下一次触发时间',
            dataIndex: 'nextFireTime',
            hideInForm: true,
            search: false,
            render: (text) => text && text !== '-1' ? moment(Number(text)).format('YYYY-MM-DD HH:mm:ss') : '不会自动触发',
        },
        {
            title: '上一次触发时间',
            dataIndex: 'prevFireTime',
            hideInForm: true,
            search: false,
            render: (text) => text ? moment(Number(text)).format('YYYY-MM-DD HH:mm:ss') : '-',
        },
        {
            title: '触发器名称',
            dataIndex: 'triggerName',
            hideInForm: true,
            hideInTable: true,
            search: false
        },
        {
            title: '触发器分组',
            dataIndex: 'triggerGroup',
            valueType: 'text',
            hideInForm: true,
            hideInTable: true,
            search: false,
        },
        {
            title: '数据更新',
            dataIndex: 'isUpdateData',
            hideInForm: true,
            search: false,
            valueType: 'select',
            valueEnum: {
                0: {text: '否', status: '0'},
                1: {text: '是', status: '1'},
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => {
              const menuItems = [
                {
                  key: 'delete',
                  label: (
                    <Tooltip placement="topLeft" title="项目重启之后删除的会重新注册回来">
                      删除
                    </Tooltip>
                  ),
                  onClick: () => {
                    Modal.confirm({
                      title: '确认删除',
                      content: (
                        <span>
                          确定要删除任务
                          <span style={{ fontWeight: 'bold', color: 'red' }}>
                            {record.jobName}
                          </span>
                          吗？
                        </span>
                      ),
                      okText: '确认',
                      okType: 'danger',
                      cancelText: '取消',
                      onOk: async () => {
                        const success = await handleRemove(record.jobName);
                        if (success) {
                          actionRef.current?.reloadAndRest?.();
                        }
                      },
                    });
                  },
                },
                {
                  key: 'pause',
                  label: record.triggerState === 'PAUSED' ? '' : '暂停',
                  onClick: async () => {
                    const success = await handlePause(record.jobName);
                    if (success) {
                      actionRef.current?.reloadAndRest?.();
                    }
                  },
                },
                {
                  key: 'resume',
                  label: record.triggerState === 'PAUSED' ? '重启' : '',
                  onClick: async () => {
                    const success = await handleResume(record.jobName);
                    if (success) {
                      actionRef.current?.reloadAndRest?.();
                    }
                  },
                },
                {
                  key: 'run',
                  label: '执行一次',
                  onClick: async () => {
                    const success = await handleRun(record.jobName);
                    if (success) {
                      actionRef.current?.reloadAndRest?.();
                    }
                  },
                },
                {
                  key: 'reset',
                  label: '重置',
                  onClick: () => {
                    handleResetModalVisible(true);
                    setStepFormValues(record);
                  },
                },
              ];

              return (
                <Dropdown menu={{ items: menuItems }}>
                  <a onClick={(e) => e.preventDefault()}>
                    操作 <DownOutlined />
                  </a>
                </Dropdown>
              );
            },
          },
    ];

    return (
        <PageContainer
            header={{
                title: '',
            }}
        >
            <ProTable<API.JobAndTriggerBO>
                headerTitle=""
                actionRef={actionRef}
                rowKey="jobName"
                search={false}
                toolBarRender={() => [
                    <Button
                        key="1"
                        type="primary"
                        onClick={() => handleRecurringModalVisible(true)}
                    >
                        添加定时任务
                    </Button>,
                    <Tooltip placement="topLeft" title="延时任务只会执行一次">
                        <Button
                            key="2"
                            type="primary"
                            onClick={() => handleDelayModalVisible(true) }
                        >
                        添加延时任务
                        </Button>
                    </Tooltip>
                   ,
                ]}
                pagination={{
                    current, // 当前页码
                    pageSize, // 每页条数
                    showSizeChanger: true, // 是否可以改变 pageSize
                    pageSizeOptions: ['5', '10', '20', '50'], // 自定义每页条数下拉选项
                    onChange: (page, pageSize) => { // 页码或 pageSize 改变的回调。
                      setCurrent(page);
                      setPageSize(pageSize);
                    },
                    onShowSizeChange: (current, size) => {// pageSize 改变的回调。
                      setCurrent(current);
                      setPageSize(size);
                    },
                  }}
                // , sorter, filter
                request={async (params) => {
                    const find: API.Pagings = {
                        pageIndex: params.current,
                        pageSize: params.pageSize,
                    };
                    const {data, success} = await pageJob({
                        ...find,
                        // FIXME: remove @ts-ignore
                        // @ts-ignore
                        // sorter,
                        // filter,
                    });
                    return {
                        data: data?.rows || [],
                        total: data?.total,
                        pageSize: data?.pageSize,
                        current: data?.currentPage,
                        success,
                    };
                }}
                columns={columns}
            />
            <CreateRecurringFormProps
                onCancel={() => handleRecurringModalVisible(false)}
                modalVisible={createRecurringModalVisible}
            >
                <ProTable<API.JobAndTriggerBO, API.JobAndTriggerBO>
                    onSubmit={async (value) => {
                        try{
                            const success = await addRecurring({
                                ...value,
                                cron: value.cronExpression,
                                jobBeanClass: value.jobClassName,
                                jName: value.jobName
                            });
                            if (success) {
                                handleRecurringModalVisible(false);
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }
                            }
                        }catch(e){
                            message.error('添加失败');
                        }
                    }}
                    rowKey="id"
                    type="form"
                    columns={columns}
                />
            </CreateRecurringFormProps>
            <CreateDelayForm
                modalVisible={createDelayModalVisible}
                jobMetasEnum={jobMetas}
                onSubmit={async (value) => {
                    try {
                        const success = await addDelay({...value  as API.AddDelay});
                        if (success) {
                            handleDelayModalVisible(false);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    } catch (error) {
                        message.error('添加失败');
                    }
                }}
                onOpenChange={(visible) => {
                    if (!visible) {
                        handleDelayModalVisible(false);
                    }
                }}
            />

            {stepFormValues && Object.keys(stepFormValues).length ? (
                <ResetJob
                    onSubmit={async (value) => {
                        if (!value.cronExpression || !value.jobName) {
                            message.error('cron表达式和任务名称不能为空');
                            return;
                          }
                        const fixedValue:API.Res = {
                            cron: value.cronExpression,
                            jName: value.jobName,
                        }
                        const success = await handleRes(fixedValue);
                        if (success) {
                            handleResetModalVisible(false);
                            setStepFormValues({});
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                    onOpenChange={(visible) => {
                        if (!visible) {
                            handleResetModalVisible(false);
                            setStepFormValues({});
                        }
                    }}
                    resetModalVisible={resetModalVisible}
                    values={stepFormValues}
                />
            ) : null}
        </PageContainer>
    );
};

export default TableList;
